/*
 * @file time_battery_info
 * @Author: liuer
 * @Date: 2024/6/3 10:09
 * @LastModified: 2024-06-03 10:09
 * @LastModifiedBy: liuer
 */
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:native_dart_package/loading/loading_util.dart';
import 'package:yt_devops/components/format_util.dart';
import 'package:yt_devops/components/gaps.dart';
import 'package:yt_devops/components/log_utils.dart';
import 'package:yt_devops/components/timer_picker.dart';
import 'package:yt_devops/components/yt_text_style.dart';
import 'package:yt_devops/components/my_gesture_detector.dart';
import 'package:yt_devops/pages/site/widgets/statistics_itme_widget.dart';
import 'package:yt_devops/resources/str_res_keys.dart';
import 'package:yt_devops/services/device/device_sevices.dart';
import 'package:yt_devops/styles/styles.dart';
import 'package:yt_devops/utils/enums.dart';

class TimeBatteryInfo extends StatefulWidget {
  final String deviceId;

  const TimeBatteryInfo(this.deviceId, {super.key});

  @override
  State<TimeBatteryInfo> createState() => _TimeBatteryInfoState();
}

class _TimeBatteryInfoState extends State<TimeBatteryInfo> {
  DeviceServices deviceServices = Get.find();
  DateTime currentDateTime = DateTime.now();
  String totalCharge = '--';
  String totalDisCharge = '--';
  List<dynamic> timeBatteryInfoList = [];
  bool isFold = true; //是否折叠
  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    _getTimeBatteryInfo();
    Log.d('_getTimeBatteryInfo=');
  }

  _getTimeBatteryInfo() async {
    var params = {
      'chargeType': 4,
      'deviceId': widget.deviceId,
      // 'deviceId': '24570239',
      'date': currentDateTime.toString().substring(0, 10)
    };
    Log.d('params==$params');
    showLoading();
    var result =
        await deviceServices.getTimeBatteryInfo(params, onError: (error) {
      dismissLoading();
      showError(error.message.toString());
      return false;
    });
    dismissLoading();
    if (result != null && result is List) {
      timeBatteryInfoList = result;
      if (timeBatteryInfoList.isNotEmpty) {
        double totalChargeNum = 0;
        double totalDisChargeNum = 0;
        for (var element in timeBatteryInfoList) {
          if (element['charge'] != null && element['charge'] is num) {
            totalChargeNum += element['charge'];
          }
          if (element['discharge'] != null && element['discharge'] is num) {
            totalDisChargeNum += element['discharge'];
          }
        }
        if (totalChargeNum > 0) {
          totalCharge = totalChargeNum.toString();
        } else {
          totalCharge = '--';
        }
        if (totalDisChargeNum > 0) {
          totalDisCharge = totalDisChargeNum.toString();
        } else {
          totalDisCharge = '--';
        }
      }
      setState(() {});
    }
  }

  @override
  Widget build(BuildContext context) {
    return Column(children: [
      Container(
        color: Colour.white,
        child: YtTimePicker(
            pickerMode: DateTimePickerMode.day,
            initialDateTime: currentDateTime,
            onChange: (date, _) {
              currentDateTime = date;
              _getTimeBatteryInfo();
            }),
      ),
      Container(
        color: Colour.white,
        child: Column(
          children: [
            Gaps.vGap8,
            Row(
              children: [
                Gaps.hGap16,
                StatisticsItemWidget(
                  ResKey.totalChargingCapacity.tr,
                  totalCharge,
                  'kWh',
                  '',
                  isHome: false,
                ),
                Gaps.hGap10,
                StatisticsItemWidget(
                    ResKey.totalDischargeCapacity.tr, totalDisCharge, 'kWh',
                    '',
                    isHome: false),
              ],
            ),
            Gaps.vGap8,
            _topTitleItem(),
          ],
        ),
      ),
      isFold
          ? Container(
              color: Colour.white,
              height: 50 * 6 + 48,
              child: Column(
                children: [
                  ListView.builder(
                    shrinkWrap: true,
                    physics: const NeverScrollableScrollPhysics(),
                    itemBuilder: (context, index) =>
                        _itemWidget(timeBatteryInfoList[index]),
                    itemCount: timeBatteryInfoList.isNotEmpty ? 6 : 0,
                  ),
                  _bottomWidget()
                ],
              ),
            )
          : Expanded(
              child: SizedBox(
              height: timeBatteryInfoList.length * 50 + 48,
              child: ListView(
                children: [
                  Container(
                    height: timeBatteryInfoList.length * 50,
                    child: ListView.builder(
                      shrinkWrap: true,
                      physics: const NeverScrollableScrollPhysics(),
                      itemBuilder: (context, index) =>
                          _itemWidget(timeBatteryInfoList[index]),
                      itemCount: timeBatteryInfoList.isNotEmpty
                          ? timeBatteryInfoList.length
                          : 0,
                    ),
                  ),
                  _bottomWidget()
                ],
              ),
            ))
    ]);
  }

  _bottomWidget() {
    return MyGestureDetector(
        onTap: () {
          setState(() {
            isFold = !isFold;
          });
        },
        child: Container(
            decoration: const BoxDecoration(
              color: Colors.white,
              borderRadius: BorderRadius.only(
                  bottomLeft: Radius.circular(10),
                  bottomRight: Radius.circular(10)),
            ),
            padding: const EdgeInsets.only(
                bottom: 10, top: 10, right: 100, left: 100),
            width: double.infinity,
            child: Image.asset(
              isFold
                  ? 'assets/images/es_arrow_down.png'
                  : 'assets/images/es_arrow_up.png',
              width: 18,
              height: 18,
            )));
  }

  // _getItems(){
  //   List<Widget> list = [];
  //   for (var element in timeBatteryInfoList) {
  //     list.add(_itemWidget(element));
  //   }
  //   list.add(MyGestureDetector(
  //       onTap: () {
  //         setState(() {
  //           isFold = !isFold;
  //         });
  //       },
  //       child: Container(
  //           decoration: const BoxDecoration(
  //             color: Colors.white,
  //             borderRadius: BorderRadius.only(
  //                 bottomLeft: Radius.circular(10),
  //                 bottomRight: Radius.circular(10)),
  //           ),
  //           padding: const EdgeInsets.only(
  //               bottom: 10, top: 10, right: 100, left: 100),
  //           width: double.infinity,
  //           child: Image.asset(
  //             isFold
  //                 ? 'assets/images/es_arrow_down.png':'assets/images/es_arrow_up.png',
  //             width: 18,
  //             height: 18,
  //           ))));
  //   return list;
  // }
  _topTitleItem() {
    return Column(
      children: [
        SizedBox(
          height: 50,
          child: Row(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: [
              Container(
                width: ScreenUtil().screenWidth / 3,
                alignment: Alignment.center,
                child: Text(
                  textAlign: TextAlign.center,
                  ResKey.deviceTimePeriod.tr,
                  style:
                      ytTextStyle(color: Colour.lightTextColor, fontSize: 14),
                ),
              ),
              Container(
                width: ScreenUtil().screenWidth / 3,
                alignment: Alignment.center,
                child: Text(
                  textAlign: TextAlign.center,
                  '${ResKey.deviceChargeCapacity.tr}(kWh)',
                  style:
                      ytTextStyle(color: Colour.lightTextColor, fontSize: 14),
                ),
              ),
              Container(
                width: ScreenUtil().screenWidth / 3,
                alignment: Alignment.center,
                child: Text(
                  textAlign: TextAlign.center,
                  '${ResKey.statisticsDisCharge.tr}(kWh)',
                  style:
                      ytTextStyle(color: Colour.lightTextColor, fontSize: 14),
                ),
              ),
            ],
          ),
        ),
        Container(
          margin: EdgeInsets.only(right: 16.w, left: 16.w),
          color: Colour.dividerColor,
          height: 0.5,
        )
      ],
    );
  }

  _itemWidget(Map map) {
    return Container(
      height: 50,
      color: Colour.white,
      child: Column(
        children: [
          SizedBox(
            height: 49,
            child: Row(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: [
                Container(
                  width: ScreenUtil().screenWidth / 3,
                  alignment: Alignment.center,
                  child: Text(
                    textAlign: TextAlign.center,
                    '${map['startTime']}-${map['endTime']}',
                    style:
                        ytTextStyle(color: Colour.mainTextColor, fontSize: 14),
                  ),
                ),
                Container(
                  width: ScreenUtil().screenWidth / 3,
                  alignment: Alignment.center,
                  child: Text(
                    textAlign: TextAlign.center,
                    map['charge'] != null
                        ? FormatUtil.commaSeparatedDigits(
                            num.parse(map['charge'].toString()))
                        : '--',
                    style:
                        ytTextStyle(color: Colour.mainTextColor, fontSize: 14),
                  ),
                ),
                Container(
                  width: ScreenUtil().screenWidth / 3,
                  alignment: Alignment.center,
                  child: Text(
                    textAlign: TextAlign.center,
                    map['discharge'] != null
                        ? FormatUtil.commaSeparatedDigits(
                            num.parse(map['discharge'].toString()))
                        : '--',
                    style:
                        ytTextStyle(color: Colour.mainTextColor, fontSize: 14),
                  ),
                ),
              ],
            ),
          ),
          Container(
            margin: EdgeInsets.only(right: 16.w, left: 16.w),
            color: Colour.dividerColor,
            height: 0.5,
          )
        ],
      ),
    );
  }
}
